package com.sy.cloud.guess.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by mac on 2018/1/12.
 */
@Controller
@Slf4j
@RequestMapping("/cookie")
public class CookieController {
    /**
     * 读取所有cookie
     * 注意二、从客户端读取Cookie时，包括maxAge在内的其他属性都是不可读的，也不会被提交。浏览器提交Cookie时只会提交name与value属性。maxAge属性只被浏览器用来判断Cookie是否过期
     * @param request
     * @param response
     */
    @RequestMapping("/showCookies")
    public void showCookies(HttpServletRequest request,HttpServletResponse response ){

        Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
        if (null==cookies) {
            log.info("没有cookie=========");
        } else {
            for(Cookie cookie : cookies){
                log.info("name:"+cookie.getName()+",value:"+ cookie.getValue());
            }
        }

    }
    /**
     * 添加cookie
     * @param response
     * @param name
     * @param value
     */
    @RequestMapping("/addCookie")
    public void addCookie(HttpServletResponse response, String name, String value){


        Cookie cookie = new Cookie(name.trim(), value.trim());
        if( name.equals("ifnewbee") ){
//            cookie.setMaxAge( 24*60 * 60 /24);// 设置为365天
            cookie.setMaxAge( 60);// 设置为60秒
        }else{
            cookie.setMaxAge(3* 24*60 * 60);// 设置为3天
        }

        cookie.setPath("/");
        System.out.println("已添加===============");
        response.addCookie(cookie);

    }



    /**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public  Cookie getCookieByName(HttpServletRequest request, String name){
        Map<String,Cookie> cookieMap = ReadCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }
    }


    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private  Map<String,Cookie> ReadCookieMap(HttpServletRequest request){
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}
